package fun.chutianshu;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException {
        List<Pet> petList =new ArrayList<>();
        //初始化游戏
        Main.initGame();
        Main.cmd_ui(petList);

    }

    private static void initGame(){
        System.out.println("#########################################################################");
        System.out.println("###                                                                   ###");
        System.out.println("###                             开心农场                                ###");
        System.out.println("###                                version：v0.1                      ###");
        System.out.println("###                                author ：xyz                       ###");
        System.out.println("###                                                                   ###");
        System.out.println("#########################################################################");
    }

    // 用户交互逻辑，除了初始化之外的游戏主进程控制，都放在下面方法中
    private static void cmd_ui(List<Pet> petList) throws IOException{
        //定义一个循环，不停的询问用户下一步要干嘛
        do{
            System.out.println("老大，接下来要干啥？");
            System.out.println("请输入下面命令中任意一项：");
            System.out.println("命令：status   功能：查看农场状态");
            System.out.println("命令：new   功能：新增宠物");
            System.out.println("命令：pk   功能：宠物单挑");
            System.out.println("命令：feed   功能：喂食宠物");
            System.out.println("命令：fly   功能：放飞宠物");
            System.out.println("命令：save   功能：存档");
            System.out.println("命令：load   功能：读档");
            System.out.println("命令：quit   功能：退出游戏");
            //获取用户输入的命令
            Scanner sc = new Scanner(System.in);
            String next_move= sc.next();
            //进入分支，根据命令来进行相应的操作
            switch (next_move){
                //显示当前玩家状态
                case "status":
                    System.out.println("当前宠物农场共有"+petList.size()+"只宠物，分别为：");
                    for (Pet pet:petList) {
                        pet.printPet();
                    }
                    break;
                //旅行
                case "new":
                    Main.newPet(petList);
                    break;
                case "pk":
                    Main.pk(petList);
                    break;
                case "feed":
                    Main.feedPets(petList);
                    break;
                case "fly":
                    Main.flyPets(petList);
                    break;
                //存档
                case "save":
                    //p是当前内存中的玩家对象
                    Main.saveGame(petList);
                    break;
                //读档
                case "load":

                    break;
                case "quit":
                    //退出游戏分支
                    System.out.println("Game Over!");
                    //用return 退出当前方法
                    return;
                default:
                    System.out.println("老大，你不认识字吗？敢敲个正确的命令不？");
            }

        }while (true);

    }

    // 存储信息到文件中
    private static void saveGame(List<Pet> petList) throws IOException {
        //实际上当前游戏比较简单，需要存储只是那些宠物信息
        //TODO：将 宠物列表 中的宠物对象信息，转换成字符串，写入本地文件中
        // 实际上有 将 json 和 对象 互相转换的第三方类库，如 fastjson 之类，但暂时我们先不用，
        // 用字符串处理来操作
        String saveStr = "";

        for (Pet pet: petList) {
            Class cls = pet.getClass();
            String className = cls.getSimpleName();
            switch (className){
                case "Dragon":
                    saveStr +="name:"+pet.getName()+",";
                    saveStr +="age:"+pet.getAge()+",";
                    saveStr +="ap:"+pet.getAp()+",";
                    saveStr +="hp:"+pet.getHp()+",";
                    saveStr +="initHp:"+pet.getInitHp()+",";
                    saveStr +="color:"+pet.getColor()+",";
                    saveStr +="rp:"+((Dragon) pet).getRp()+",";
                    saveStr +="\n";
                    break;
                case "Phenix":
                    saveStr +="name:"+pet.getName()+",";
                    saveStr +="age:"+pet.getAge()+",";
                    saveStr +="ap:"+pet.getAp()+",";
                    saveStr +="hp:"+pet.getHp()+",";
                    saveStr +="initHp:"+pet.getInitHp()+",";
                    saveStr +="color:"+pet.getColor()+",";
                    saveStr +="isReborn:"+((Phenix) pet).isReborn()+",";
                    saveStr +="\n";
                    break;
                case "Tiger":
                    saveStr +="name:"+pet.getName()+",";
                    saveStr +="age:"+pet.getAge()+",";
                    saveStr +="ap:"+pet.getAp()+",";
                    saveStr +="hp:"+pet.getHp()+",";
                    saveStr +="initHp:"+pet.getInitHp()+",";
                    saveStr +="color:"+pet.getColor()+",";
                    saveStr +="\n";
                    break;
                case "Turtle":
                    saveStr +="name:"+pet.getName()+",";
                    saveStr +="age:"+pet.getAge()+",";
                    saveStr +="ap:"+pet.getAp()+",";
                    saveStr +="hp:"+pet.getHp()+",";
                    saveStr +="initHp:"+pet.getInitHp()+",";
                    saveStr +="color:"+pet.getColor()+",";
                    saveStr +="shellNum:"+((Turtle) pet).getShellNum()+",";
                    saveStr +="\n";
                    break;
            }
        }

        try (Writer writer = new OutputStreamWriter(new FileOutputStream("player_save.save"), "UTF-8")) {
            writer.write(saveStr); // 写入String
        }
    }
    /*
    // 读档方法
    public static void loadGame() throws IOException {
        //创建 reader 对象
        try (Reader reader = new InputStreamReader(new FileInputStream("player_save.save"), "UTF-8")) {
            // 创建缓冲区，可以一次将文件中内容读入内存缓冲区中
            char[] buffer = new char[1000];
            int n;
            String s="";
            //读取文件内容到缓冲区，并转换为字符串
            while ((n = reader.read(buffer)) != -1) {
                //一共读了多少个字符
                System.out.println("read " + n + " chars.");
                //将缓冲区内容存入字符串，方便后续处理，并去除空字符
                s = String.valueOf(buffer).trim();
                //打印字符串
                System.out.println(s);
            }
            //分割字符串，并将其中信息读入 p 当前玩家对象汇总
            if(s!=""){
                //创建 HashMap 对象，来存储玩家字段信息，字段名为key，字段值是 value
                HashMap<String,String> hashMap = new HashMap<>();
                // 将字符串按 ; 分割,存入字符数组
                String[] strArray = s.split(";");
                // 通过遍历，将字符串数组中的每一项，转换为 HashMap 中的一个键值对
                for(String pair:strArray) {
                    //将字符串按 : 分割，区分 key 和 value
                    String[] subArray = pair.split(":");
                    // 将子字符数组中的索引0 当做 Key， 索引1 当做 value 建立 HashMap 中的各个项
                    hashMap.put(subArray[0], subArray[1]);
                }
                //设置内存中当前玩家对象的各个字段值
                p.setName(hashMap.get("name"));
                p.setX(Integer.parseInt(hashMap.get("x")));
                p.setY(Integer.parseInt(hashMap.get("y")));
                p.setHp(Integer.parseInt(hashMap.get("hp")));
                p.setAp(Integer.parseInt(hashMap.get("ap")));
                p.setSp(Integer.parseInt(hashMap.get("sp")));
                System.out.println("读档成功！");
            }
        }
    }
    */

    // 新增宠物
    private static void newPet(List<Pet> petList){
        System.out.println("新增宠物：");
        Pet newPet = null;
        Scanner sc = new Scanner(System.in);




        boolean newPetNotDone = true;
        do {
            System.out.println("请输入宠物名：");
            String petName= sc.next();
            System.out.println("请输入宠物生命：");
            int petHp= sc.nextInt();
            System.out.println("请输入宠物年龄：");
            int petAge= sc.nextInt();
            System.out.println("请输入宠物攻击力：");
            int petAp= sc.nextInt();
            System.out.println("请输入宠物颜色：");
            String petColor= sc.next();
            System.out.println("请选择要增加的宠物类型：1.龙，2.凤，3.虎，4.龟(输入对应编号即可)");
            String petType= sc.next();
            switch (petType) {
                case "1":
                    System.out.println("请输入这条龙的降雨量：");
                    int petRp = sc.nextInt();
                    newPet = new Dragon(petAge, petName, petHp, petColor, petAp, petRp);
                    newPet.printPet();
                    newPetNotDone = false;
                    break;
                case "2":
                    newPet = new Phenix(petAge, petName, petHp, petColor, petAp);
                    newPet.printPet();
                    newPetNotDone = false;
                    break;
                case "3":
                    newPet = new Tiger(petAge, petName, petHp, petColor, petAp);
                    newPet.printPet();
                    newPetNotDone = false;
                    break;
                case "4":
                    System.out.println("请输入这只玄武的龟甲数：");
                    int petShellNum = sc.nextInt();
                    newPet = new Turtle(petAge, petName, petHp, petColor, petAp, petShellNum);
                    newPet.printPet();
                    newPetNotDone = false;
                    break;
                default:
                    System.out.println("你输入的编号不正确，请重新输入");
            }
        }while(newPetNotDone);

        petList.add(newPet);
        System.out.println("新宠物已被添加如你的宠物农场！");
    }

    // 宠物pk
    private static void pk(List<Pet> petList){
        if(petList.size()==0){
            System.out.println("农场中并无宠物，打空气吗？你傻啊！");
            return;
        }
        //创建 hashmap
        Map<String,Pet> petMap = new HashMap();


        int i = 1;
        for (Pet pet:petList) {
            if(pet.getHp()>0)
            {
                petMap.put(Integer.toString(i),pet);
                i++;
            }
        }
        if(i<3){
            System.out.println("农场里现在活着的宠物不足两只，打不了！");
            return;
        }
        System.out.println("当前要可以进行pk的宠物有：");
        for (Map.Entry<String,Pet> entry:petMap.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue().getName());
        }

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入第一要选择的宠物编号：");
        String keyA= sc.next();
        Pet petA = petMap.get(keyA);
        System.out.println("你选择的第一个pk宠物是:");
        petA.printPet();
        System.out.println("请输入第二要选择的宠物编号：");
        String keyB= sc.next();
        Pet petB = petMap.get(keyB);
        System.out.println("你选择的第二个pk宠物是:");
        petB.printPet();

        //开打
        System.out.println("宠物开始pk！！！！！！！！！！！！");
        //循环打斗，直到其中之一挂掉为止
        do{
            petA.attack(petB);
            if(petB.getHp()>0) {
                petB.attack(petA);
                if(petA.getHp()<=0){
                    System.out.println(petA.getName()+"挂了！"+petB.getName()+"赢得胜利！");
                }
            }
            else {
                System.out.println(petB.getName()+"挂了！"+petA.getName()+"赢得胜利！");
            }
        }while (petA.getHp()>0&&petB.getHp()>0);

    }

    // 喂食宠物
    private static void feedPets(List<Pet> petList){
        Boolean isContinue = true;
        do{
            Food food = new Food(10,"牛肉");
            System.out.println("你要喂一只(1)，还是一次全都喂(2),请输入对应序号：");
            Scanner sc = new Scanner(System.in);
            String str = sc.next();

            switch (str){
                case "1":
                    if(petList.size()==0){
                        System.out.println("农场中并无宠物！");
                        return;
                    }
                    //创建 hashmap
                    Map<String,Pet> petMap = new HashMap();

                    int i = 1;
                    for (Pet pet:petList) {
                        if(pet.getHp()>0)
                        {
                            petMap.put(Integer.toString(i),pet);
                            i++;
                        }
                    }
                    if(i<2){
                        System.out.println("农场里没有活着的宠物，无法喂食！");
                        return;
                    }
                    System.out.println("当前要可以进行喂食的宠物有：");
                    for (Map.Entry<String,Pet> entry:petMap.entrySet()) {
                        System.out.println(entry.getKey()+":"+entry.getValue().getName());
                    }

                    System.out.println("请输入第一要选择的宠物编号：");
                    String key= sc.next();
                    Pet pet = petMap.get(key);

                    pet.eat(food);
                    System.out.println("是否继续喂食（y/n）");
                    String strYN = sc.next();
                    if(strYN.equals("y"))
                    {
                        isContinue = true;
                    }
                    else{
                        isContinue = false;
                    }
                    break;
                case "2":
                    if(petList.size()==0){
                        System.out.println("农场中并无宠物！");
                        return;
                    }
                    //创建 hashmap
                    Map<String,Pet> petMap2 = new HashMap();

                    int j = 1;
                    for (Pet pet1:petList) {
                        if(pet1.getHp()>0)
                        {
                            petMap2.put(Integer.toString(j),pet1);
                            j++;
                        }
                    }
                    if(j<2){
                        System.out.println("农场里没有活着的宠物，无法喂食！");
                        return;
                    }
                    System.out.println("投喂结果：");
                    for (Map.Entry<String,Pet> entry:petMap2.entrySet()) {
                        System.out.println(entry.getKey()+":"+entry.getValue().getName());
                        entry.getValue().eat(food);
                    }
                    System.out.println("是否继续喂食（y/n）");
                    String strYN2 = sc.next();
                    if(strYN2.equals("y"))
                    {
                        isContinue = true;
                    }
                    else{
                        isContinue = false;
                    }
                    break;
                default:
                    System.out.println("只能输入1或2，请重新输入！");
            }
        }while (isContinue);
    }
    // 放飞
    private static void flyPets(List<Pet> petList) {
        if(petList.size()==0){
            System.out.println("农场中并无宠物！");
            return;
        }
        //创建 hashmap
        Map<String,Fly> flyMap = new HashMap();

        int i = 1;
        for (Pet pet:petList) {
            if(pet.getHp()>0&&(pet instanceof Dragon || pet instanceof Phenix))
            {
                flyMap.put(Integer.toString(i),(Fly) pet);
                i++;
            }
        }
        if(i<2){
            System.out.println("农场里没有活着的会飞的宠物，无法放飞！");
            return;
        }
        System.out.println("开始放飞：");
        for (Map.Entry<String,Fly> entry:flyMap.entrySet()) {
            System.out.println(entry.getKey()+":"+((Pet)entry.getValue()).getName());
            entry.getValue().fly();
        }
    }
}
